package com.mdp.tpa.wechat.wxpub.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mdp.tpa.wechat.api.SecurityService;
import com.mdp.tpa.wechat.wxpub.service.WxNotifyService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.mdp.core.utils.DistinctUtil;

@RestController("wxpub.wxNotifyController")
@RequestMapping(value="/wxpub/msg")
public class WxNotifyController {
	
	private Log log=LogFactory.getLog(WxNotifyController.class);
	@Autowired
	WxNotifyService wxNotifyService;
	
	@Autowired
	SecurityService wxApiSecurity;
	
	int maximumSize = 10000;
	LinkedHashMap<String, String> msgMap= new LinkedHashMap<String, String>() {
			private static final long serialVersionUID = 1L;
			@Override
	        protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
	            return size() > maximumSize;
	        }
	    };
	
	/**
	 * 微信消息发送到开发商服务端,get,一般修改公众平台上的EncodingAESKey，Token,消息加密方式等，会使用get方式推送信息到本函数。
	 * 首次服务器验证 微信发过来的信息
	 * {timestamp=1478231323, echostr=2293813022107307999, nonce=320121891, signature=ef7a44ee63872eef9aeb01e5a26f7ed13f216eef}
	 * @author cyc
	 **/
	@RequestMapping(value="/notify",method=RequestMethod.GET)
	public void notifyDev(@RequestParam Map<String,Object> params, HttpServletRequest request, HttpServletResponse response) throws IOException {
		 
		String result="";
		//Map<String,Object> map=super.getData();
		// 微信加密签名 
        String signature =(String)params.get("signature");
        // 时间戳
        String timestamp = (String)params.get("timestamp");
        // 随机数
        String nonce = (String)params.get("nonce");
        
        // 第三方appid
        String authId = (String)params.get("authId");
		PrintWriter out = response.getWriter();
        // 随机字符串
        String echostr =request.getParameter("echostr");
		log.debug("收到微信公众平台消息： {timestamp="+timestamp+", echostr="+echostr+", nonce="+nonce+", signature="+signature+"}" );
		try {
			result=wxApiSecurity.verifyUrl(signature, timestamp,nonce, echostr);
			out.print(echostr);
		} catch (Exception e) {
			 log.error("",e);
			out.print(echostr);
		}finally {
			out.close();
			out.print(echostr);
		}
		log.debug("回复给微信公众平台消息："+echostr);
	}
	
	/**
	 * 微信消息发送到开发商服务端,post,处理明文方式的推送消息
	 */
	@RequestMapping(value="/notify",method=RequestMethod.POST)
	public void notifyDev2(@RequestParam Map<String,Object> params,@RequestBody String context,HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		try {
			out.print("success");
		} catch (Exception e) {
			log.error("",e);
		}finally {
			out.close();
		}
		if(DistinctUtil.isDistinct((String)params.get("FromUserName")+params.get("CreateTime"))){
			return;
		};
		log.debug("收到微信公众平台消息："+params.toString()+" context:"+context);
		
	}
	
	/**
	 * 微信消息发送到开发商服务端,post,处理密文方式的推送消息
	 * 收到微信公众平台消息：
	 明文模式下：{} 
	 context:
	 <xml><URL><![CDATA[http://www.qingqinkj.com/coa/pubplat/wxmsg/notifyDev]]></URL><ToUserName><![CDATA[cycsir8]]></ToUserName><FromUserName><![CDATA[cycsir1]]></FromUserName><CreateTime>201020102012</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[aaaadfdafd]]></Content><MsgId>111111111</MsgId></xml>

	 兼容模式下:
	  {timestamp=1478359677, encrypt_type=aes, nonce=529253978, msg_signature=47a58b72302575eda0fa1ec44de4c192e7d6c128, signature=da012e46e60cc0ce0a6993149ac9f9965d124760} 
	 context:
	 <xml>
	    <URL><![CDATA[http://www.qingqinkj.com/coa/pubplat/wxmsg/notifyDev]]></URL>
	    <ToUserName><![CDATA[cycsir8]]></ToUserName>
	    <FromUserName><![CDATA[cycsir1]]></FromUserName>
	    <CreateTime>201020102012</CreateTime>
	    <MsgType><![CDATA[text]]></MsgType>
	    <Content><![CDATA[aaaadfdafd]]></Content>
	    <MsgId>111111111</MsgId>
	    <Encrypt><![CDATA[/U0fQ8Oc83YJnVi/DFHes4qs3je8Zn5l/rGx++aLFY/qt1FptOgr+epqfDEfDdDVhS0BFJ6wSENrAxudgAaJW7dn69b/iTujANgRG96AD31qEYS4MjP4/6jGux1P3wWCxkFCYS+rKrD/Mn/Rrjbt3A8yRxvfO1jPP1YLZoN71o3b4k4n/4VwYk575PRBG5YbDr/brzrvbC7sR7Ko/KCQFe1B0eCqvmnzeWYCZM7tPQfUwXRD8uPtgQK9dc3hdeXVU+f18M5uVObhWZdCOUIDGSLhk5Nb/8gmXarCYExQVbHX57BiKn8/U7E/Bcey4XBV9JVvC2RjcJtpiEqtQzm6O1lmi1NJyLM5ms3NBagznQ1wFAO1ReRaM231p+lzOYQ7hG+Rf9GrzGqzbxJsD7sYVaf7UQgha9JtSmVQU/clLPSpRRNdMUN9d4VrtowfaXKh3eBe1EhKqvMQKKarvJxrudQit71SD/WnUtA/hAV20+jxr3ihhcjeKZb8ONTybNXw]]></Encrypt>
	</xml>
	
	安全模式下：
	{timestamp=1478360294, encrypt_type=aes, nonce=977811974, msg_signature=b47d5e8f5c632fd20338b802d8b16073685cfa97, signature=34faffdcbacc2d4507221ddf9e1b6a27dd82a463} 
	context:
	<xml>
    <ToUserName><![CDATA[cycsir8]]></ToUserName>
    <Encrypt><![CDATA[Cm0VWmSOkJZ1HjwGdNBE1OZGbxgbTciF+dPzoTRZvArN10UAkPCK/a+IhY4kC5m0h3MKUMOP1PEmlpFcoc4w0oiYKivtJAV/6Bcp12i+hSMY5bhLqmYPZDjEwKvIggik/mwVssRT3eRSEqAktznf53JqHqqtNrzpXu97Nz1/AU4DO9gzFOoXSsFaw2wHLmGqdzTMXyrMsooI6tDosauV6A1XXyjdZae9EQ9LI6ooQC6cLtLVBThCuYEvZ1Hmr/7Ue7HZIuW5mbs/EYRkg4qCe5TOecgsDuM2/Ytodf4ANP3OrD0UFvm+Pfs9MxX9q8aCCotyDXOt6QaX7YVUIowfVHaROo1xAF6pgD7HgTNqHwO1nFl4KI+bezNm2eLLWXw4RLDqRoMLl+FOMYY2/M0+v5ITKdkw7qLvR4bsmVpgJRWzLIfLAoxUJZIYrkG0pgQT6oL1NGpczFZhOa4rjshDftFZJmiGrwVGfT+WmTK1oRUwtoRzIMjHUIw13lBTwKcW]]></Encrypt>
	</xml>
	 */
	@RequestMapping(value="/notify",method=RequestMethod.POST,params={"signature","timestamp","nonce"})
	public void notifyDev3(@RequestBody   String context,   String timestamp,  String nonce,  String msg_signature,String signature,String authId,HttpServletRequest request, HttpServletResponse response) throws IOException {
		log.debug("收到微信公众平台消息：{timestamp="+  timestamp+",nonce="+ nonce+",msg_signature="+ msg_signature +",signature="+ signature +"} \n 报文体＝"+context);
		String echostr="success";
		String charset="utf-8";
		String farCharset="ISO-8859-1";
		PrintWriter out = response.getWriter();
		try {
			 
			//需要考虑使用异步处理，提高微信使用效率
			if(DistinctUtil.isDistinct(signature)){
				String mingWenXml= context;
				if(!StringUtils.isEmpty(msg_signature)) {
					mingWenXml=wxApiSecurity.decryptMsg(msg_signature, timestamp,nonce,context);
					log.info("解密后的明文报文体＝"+mingWenXml); 
				} 
				echostr=wxNotifyService.getMsgForReplyToWeiXin(mingWenXml);
				
				echostr = charsetString(echostr,charset,farCharset);
				out.print(echostr);
				log.debug("回复给微信公众平台消息，字符编码为["+farCharset+"]："+echostr);
			}else{
				out.print(echostr);
			}
			
		} catch (Exception e) {
			try {
				out.print(echostr);
			} catch (Exception e1) {
				log.error(e1);
			}
			 log.error("",e);
		}finally {
			out.close();
		}
	}
 
	
	/**
	 * 字符集转换
	 * @param str
	 * @param fromCharset
	 * @param toCharset
	 * @return
	 */
	public String charsetString(String str,String fromCharset,String toCharset){
		if(str==null){
			return null;
		}
		if(fromCharset!=null && fromCharset.equalsIgnoreCase(toCharset)){
			return str;
		}else if(fromCharset!=null && toCharset!=null){
			try {
				return new String(str.getBytes(fromCharset),toCharset);
			} catch (UnsupportedEncodingException e) {
				 log.error("",e);
				 return str;
			}
		}else if(fromCharset==null && toCharset!=null){
			try {
				str=new String(str.getBytes(),toCharset);
				return str;
			} catch (UnsupportedEncodingException e) {
				 log.error("",e);
				 return str;
			}
		}else if(fromCharset!=null && toCharset==null){
			try {
				str=new String(str.getBytes(fromCharset));
			} catch (UnsupportedEncodingException e) {
				 log.error("",e);
				 return str;
			}
		}
		return str;
	}
}
